﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Helpers;
using System.Collections.Generic;
using Model;
using System.IO;

namespace FEIStorageSite
{
    public partial class Download : System.Web.UI.Page
    {
        public FileItem file;
        List<CategoryItem> categoriesList;

        public void DownloadDataPagerPreRender(object sender, EventArgs e)
        {
            if (Request["type"] == "category")
            {
                int categoryID = Convert.ToInt32(Request["id"]);
                List<FileItem> files = DAL.GetFilesList(categoryID);
                downloadPageTitle.Text = "<h3>" + DAL.GetCategoryName(categoryID) + "</h3>";

                if (files.Count == 0)
                {
                    downloadPageError.Text = "В даній категорії поки що немає файлів";
                }
                else
                {
                    foreach (FileItem curFileItem in files)
                    {
                        try
                        {
                            string filePath2 = Server.MapPath(curFileItem.Path);
                            FileInfo curfileInfo = new FileInfo(filePath2);
                            curFileItem.FileSize = curfileInfo.Length.ToString();
                        }
                        catch (Exception exception)
                        {
                            curFileItem.FileSize = "0";
                        }
                    }

                    filesListView.DataSource = files;
                    filesListView.DataBind();
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            DAL.connectionString = "Data Source=" + Server.MapPath("App_Data\\fei_storage.db");
            try
            {
                switch (Request["type"])
                {
                    case "download":
                        FileItem fileToDownload = DAL.GetFile(Convert.ToInt32(Request["id"]));
                        string filePath = Server.MapPath(fileToDownload.Path);
                        FileInfo fileInfo = new FileInfo(filePath);
                        if (fileInfo.Exists)
                        {
                            fileToDownload.IncDownCount();
                            DAL.EditFile(fileToDownload);
                            Response.ClearContent();
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                            Response.ContentType = ReturnExtension(fileInfo.Extension.ToLower());
                            Response.TransmitFile(fileInfo.FullName);
                            Response.End();
                        }
                        break;
                    case "file":                        
                        int fileID = Convert.ToInt32(Request["id"]);
                        categoriesList = DAL.GetCategories();
                        FileItem file = DAL.GetFile(fileID);
                        downloadPageTitle.Text = "<h3>Download file</h3>";
                        fileNameView.InnerText = file.Name;

                        try
                        {
                            string filePath1 = Server.MapPath(file.Path);
                            FileInfo fileInfo1 = new FileInfo(filePath1);
                            file.FileSize = fileInfo1.Length.ToString();
                        }
                        catch (Exception exception)
                        {
                            file.FileSize = "0";
                        }

                        fileSizeView.InnerText = file.FileSize;
                        fileDescriptionView.InnerText = file.Description;
                        fileDownCountView.InnerText = file.DownCount.ToString();
                        fileCategoryNameView.InnerText = categoriesList.Find(delegate(CategoryItem item) { return file.CategoryID == item.ID; }).Name.ToString();
                        fileDateView.InnerText = file.Date.ToString();
                        downButton.HRef = "Download.aspx?type=download&id=" + file.ID;
                        fileView.Visible = true;
                        break;

                    case "category":

                        break;

                    default:
                        downloadPageTitle.Text = "<h3>Виберіть категорію:</h3>";
                        categoriesListView.DataSource = DAL.GetCategories();
                        categoriesListView.DataBind();
                        break;
                }                
            }
            catch (Exception exception)
            {

            }
        }

        private string ReturnExtension(string fileExtension)
        {
            switch (fileExtension)
            {
                case ".htm":
                case ".html":
                case ".log":
                    return "text/HTML";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".tiff":
                case ".tif":
                    return "image/tiff";
                case ".asf":
                    return "video/x-ms-asf";
                case ".avi":
                    return "video/avi";
                case ".zip":
                    return "application/zip";
                case ".xls":
                case ".csv":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".mp3":
                    return "audio/mpeg3";
                case ".mpg":
                case "mpeg":
                    return "video/mpeg";
                case ".rtf":
                    return "application/rtf";
                case ".asp":
                    return "text/asp";
                case ".pdf":
                    return "application/pdf";
                case ".fdf":
                    return "application/vnd.fdf";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                case ".msg":
                    return "application/msoutlook";
                case ".xml":
                case ".sdxl":
                    return "application/xml";
                case ".xdp":
                    return "application/vnd.adobe.xdp+xml";
                default:
                    return "application/octet-stream";
            }
        }
    }
}
